<?php

namespace App\Http\Controllers\Api;

use App\AdvertImg;
use App\Banner;
use App\Distribution;
use App\Express;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\SearchKeywordRecord;
use App\Shops;
use App\ShowGoods;
use App\SysSetUp;
use App\User;
use App\UserInfo;
use App\UserSearchRecord;
use App\VipRule;
use App\Withdraw;
use Illuminate\Bus\Dispatcher;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class OtherController extends Controller
{
    /**
     * 获取banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBannerList(Request $request){
        $allBanner = Banner::whereStatus(1)->orderBy("sort","asc")->orderBy("created_at","desc")->get();
        if(count($allBanner) > 0){
            foreach ($allBanner as $banner){
                /** @var Banner $banner */
                $banner->img_url = FileManager::getImgUrl($banner->img_id);
            }
        }

        return response()->json(["level"=>"success","message"=>"获取成功","data"=>$allBanner]);
    }

    /**
     * 获取店铺列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page'  => $page
        ];

        /** @var Shops $shop */
        $shopList = Shops::whereNull('deleted_at');

        $pageInfo['total'] = $shopList->count();

        $shopList = $shopList->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($shopList) > 0){
            foreach($shopList as $shop){
                $shop->thumb_url = FileManager::getImgUrl($shop->thumb_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $shopList,'page_info' => $pageInfo]);
    }

    /**
     * 获取快递公司
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpressCompany ()
    {
        $express = Express::whereIsDefault(1)->first();

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $express]);
    }

    /**
     * 获取店铺详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $shop = Shops::whereId($id)->first();
        if($shop){
            $shop->thumb_url = FileManager::getImgUrl($shop->thumb_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $shop]);
    }

    /**
     * 获取关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function gerAboutUs(Request $request){
        $aboutUs = SysSetUp::whereType(0)->first();
        if($aboutUs){
            $aboutUs->content = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$aboutUs->content);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $aboutUs]);
    }

    /**
     * 获取服务协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getServiceAgreement(Request $request){
        $serviceAgreement = SysSetUp::whereType(1)->first();
        if($serviceAgreement){
            $serviceAgreement->content = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$serviceAgreement->content);

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $serviceAgreement]);
    }

    /**
     * 拼团规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupRule(Request $request){
        $groupRule = SysSetUp::whereType(3)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $groupRule]);
    }

    /**
     * 获取首页广告图
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdvertImg (Request $request)
    {
        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'common';
        /** @var AdvertImg $advertImg */
        $allAdvertImg = AdvertImg::whereType($type)->orderBy('sort', 'asc')->orderBy('created_at', 'desc')->get();
        if (count($allAdvertImg) > 0) {
            foreach ($allAdvertImg as $advertImg) {
                $advertImg->img_url = FileManager::getImgUrl($advertImg->img_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allAdvertImg]);
    }

    public function searchSomething(Request $request){
        $user = UserManager::isLogin($request);
        $keyword    = $request->get('keyword');
        $page   =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit  =!is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page_info=[
            'page'          =>$page,
            'limit'         =>$limit,
            'demand_total'  =>0,
            'news_total'    =>0,
            'unit_total'    =>0,
        ];
        $page=$page-1;
        $result=[
            'demand'  =>[],
            'news'    =>[]
        ];

        if (!trim($keyword))
            return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$result]);
        //TODO 记录搜索关键词
        $user_id = $user ? $user->id : 0;
        self::addSearchRecord($keyword,$user_id,$request->ip());
        $Demand = Demands::where('title','like','%'.trim($keyword).'%')
            ->orWhere('content','like','%'.trim($keyword).'%');
        $page_info['demand_total']=$Demand->count();
        $demands =$Demand->offset($page * $limit)->limit($limit)->get();

        $news   =News::where('title','like','%'.trim($keyword).'%')
            ->orWhere('desc','like','%'.trim($keyword).'%')
            ->orWhere('info','like','%'.trim($keyword).'%');
        $page_info['news_total']=$news->count();
        $news   =$news->offset($page * $limit)->limit($limit)->get(['id','title','img_id','desc','type','video_id','advert_img_id','created_at']);

        $vip_unit=Units::where('name','like','%'.trim($keyword).'%');
        $page_info['unit_total']=$vip_unit->count();
        $vip_unit=$vip_unit->offset($page * $limit)->limit($limit)->get();
        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $classify               =Classify::whereId($demand->classify_id)->first();
                $industry               =Industries::whereId($demand->industry_id)->first();
                $imgs                   =DemandImg::whereDemandId($demand->id)->get();
                $url_array=[];
                if (count($imgs) > 0){
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;


            }
        }
        if (count($news) > 0){
            /** @var News $item */
            foreach ($news as $item){
                $item->img_url          =FileManager::getImgUrl($item->img_id);
                $item->advert_img_url   =FileManager::getImgUrl($item->advert_img_id);
                $item->video_url        =FileManager::getVideoUrl($item->video_id);
                $item->lable_array      =NewsLabel::whereNewsId($item->id)->pluck('name')->toArray();
//                $item->comments=$comments;
            }
        }
        if (count($vip_unit) > 0){
            foreach ($vip_unit as $item){
                $industry           =Industries::whereId($item->industry_id)->first();
                $item->photo_url    =FileManager::getImgUrl($item->photo_id);
                $item->industry_name=$industry ? $industry->name : '其他';
            }
        }
        $result['demand']   =$demands;
        $result['news']     =$news;
        $result['vip_unit'] =$vip_unit;
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$result]);

    }

    public function getSearchKeyword(Request $request){
        $user       = UserManager::isLogin($request);
        $user_id    = $user ? $user->id : 0;
        if ($user_id){
            $user_keyword   =UserSearchRecord::whereUserId($user_id)->orderBy('id','desc')->offset(0)->limit(8)->pluck('keyword')->toArray();
        } else {
            $user_keyword   =[];
        }
        $keyword            =SearchKeywordRecord::orderBy('number','desc')->offset(0)->limit(6)->pluck('keyword')->toArray();

        $result=[
            'my_history'        =>$user_keyword,
            'recommend_keyword' =>$keyword
        ];
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result]);


    }

    public function delMykeywordRecord(Request $request){
        $user       = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $user_keyword   =UserSearchRecord::whereUserId($user->id)->delete();
        return response()->json(['level'=>'success','message'=>'清除成功']);

    }
    public static function addSearchRecord($keyword,$user_id=0,$ip=''){
        if ($keyword){
            if ($user_id){
                $thisRecord = UserSearchRecord::whereKeyword($keyword)->whereUserId($user_id)->orderBy('created_at','desc')->first();
                if($thisRecord){
                    if(strtotime($thisRecord->created_at) + 300 <= time()){
                        $thisRecord             = new UserSearchRecord();
                        $thisRecord->user_id    = $user_id;
                        $thisRecord->keyword    = $keyword;
                        if ($ip)
                            $thisRecord->ip     = $ip;
                        $thisRecord->save();
                    }
                } else {
                    $thisRecord = new UserSearchRecord();
                    $thisRecord->user_id   = $user_id;
                    $thisRecord->keyword   = $keyword;
                    if ($ip)
                        $thisRecord->ip    = $ip;
                    $thisRecord->save();
                }
            }
            $keyword_num = SearchKeywordRecord::whereKeyword($keyword)->first();
            if ($keyword_num){
                $keyword_num->number    =$keyword_num->number+1;
                $keyword_num->save();
            } else {
                $keyword_num            =new SearchKeywordRecord();
                $keyword_num->keyword   =$keyword;
                $keyword_num->save();
            }


        }
        return 1;
    }
}
